package com.ityy.ruiji.controller;

import com.ityy.ruiji.common.R;
import com.ityy.ruiji.entity.User;
import com.ityy.ruiji.service.UserService;
import com.ityy.ruiji.utils.SMSUtils;
import com.ityy.ruiji.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * 作用：发送短信
     * url:http://localhost:8080/user/sendMsg
     * method: post
     * 请求参数： json（手机号）
     * 返回值类型：R
     */
    @PostMapping("/sendMsg")
    public R sendMsg(@RequestBody User user, HttpSession session){
       //1. 生成四位验证码
        String code = "0413";//ValidateCodeUtils.generateValidateCode(6);
        //2. 调用工具类发送短信
        String phone = user.getPhone();
        //SMSUtils.sendMessage("黑马旅游网", "SMS_205126318", phone, code + "");
        log.info("本次验证码："+ code);
        //3. 验证码需要存储session中
        session.setAttribute(phone,code+"");
        //4. 返回发送成功
        return R.success("发送成功");
    }

    @PostMapping("/login")
    public R userLogin(@RequestBody Map<String,Object> paramMap, HttpSession httpSession){
        String phone = (String) paramMap.get("phone");
        String code = (String) paramMap.get("code");
        String attribute = (String) httpSession.getAttribute(phone);
        R result = userService.login(phone, code, attribute);
        if (result.getCode()==1){
            httpSession.removeAttribute(phone);
            User user = (User) result.getData();
            httpSession.setAttribute("user",user.getId());
        }


        return result;
    }

}
